import React, { Component } from 'react';

class LifecycleIn extends Component {
  // 挂载阶段
  constructor(props) {
    super(props);
    this.state = {date: new Date()}
    console.log('---- 挂载阶段 start ----')
    console.log('constructor');
  }

  // componentWillMount() {
  //   // 不安全的
  //   console.log('componentWillMount')
  // }

  static getDerivedStateFromProps(props, state) {
    console.log('getDerivedStateFromProps');
    if (props.name === 'React') {
      return {
        date: new Date()
      }
    }
    return null;
  }

  componentDidMount() {
    // 挂载时的生命周期钩子
    console.log('componentDidMount');
    console.log('---- 挂载阶段 end ----');
  }

  // 更新阶段

  // componentWillReceiveProps() {
  //   // 不安全的
  //   console.log('---- 更新阶段 start ----')
  //   console.log('componentWillReceiveProps');
  // }

  shouldComponentUpdate() {
    console.log('shouldComponentUpdate');
    return true;
  }

  // componentWillUpdate() {
  //   // 不安全的
  //   console.log('componentWillUpdate');
  // }

  getSnapshotBeforeUpdate() {
    console.log('getSnapshotBeforeUpdate');
    return 'getSnapshotBeforeUpdate';
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log(`componentDidUpdate - ${snapshot}`);
    console.log('---- 更新阶段 end ----');
  }

  componentWillUnmount() {
    // 组件卸载时的生命周期钩子
    console.log('---- 卸载阶段 end ----');
    console.log('componentWillUnmount');
    console.log('---- 卸载阶段 end ----');
  }

  tick = () => {
    console.log('---- 更新阶段 start ----')
    this.setState({
      date: new Date()
    });
  }

  render() {
    console.log('render');
    return (
      <div>
        <button onClick={this.tick}>修改state</button>
        <p>Hello {this.props.name}!</p>
        <p>{this.state.date.toLocaleTimeString()}</p>
      </div>
    );
  }
}

export default class Lifecycle extends Component {
  state = {
    name: 'World',
  }

  changeLifecycleName = () => {
    this.setState({
      name: this.state.name === 'React' ? 'World' : 'React',
    })
  }

  render() {
    return (
      <div>
        <button onClick={this.changeLifecycleName}>修改props</button>
        <LifecycleIn name={this.state.name} /> 
      </div>
    )
  }
}